﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace iNet.Media.Imaging.Bmp
{
	#region BitmapFileHeader
	/// <summary>
	/// BMP 檔案標頭。
	/// </summary>
	[StructLayout(LayoutKind.Sequential)]
	public struct BitmapFileHeader
	{
		#region 欄位
		public ushort Type;
		public uint Size;
		public ushort Reserved1;
		public ushort Reserved2;
		public uint OffBits;
		#endregion
		#region 建構子
		/// <summary>
		/// 使用指定資料流初始化 BitmapFileHeader 結構欄位。
		/// </summary>
		/// <param name="stream">提供資料讀取的資料流。</param>
		public BitmapFileHeader(Stream stream)
			: this(stream, false)
		{ }
		/// <summary>
		/// 使用指定資料流初始化 BitmapFileHeader 結構欄位。
		/// </summary>
		/// <param name="stream">提供資料讀取的資料流。</param>
		/// <param name="restorePosition">讀取完成後是否恢復資料流位置。</param>
		public BitmapFileHeader(Stream stream, bool restorePosition)
		{
			//確認
			if (stream == null)
				throw new ArgumentNullException("stream");

			//讀取
			byte[] buffer = new byte[14];
			if (stream.Read(buffer, 0, 14) < 14)
				throw new EndOfStreamException();
			if (restorePosition && stream.CanSeek)
				stream.Seek(-14, SeekOrigin.Current);
			BitConverter converter = BitConverter.LittleEndian;
			this.Type = converter.ToUInt16(buffer, 0);
			this.Size = converter.ToUInt32(buffer, 2);
			this.Reserved1 = converter.ToUInt16(buffer, 6);
			this.Reserved2 = converter.ToUInt16(buffer, 8);
			this.OffBits = converter.ToUInt32(buffer, 10);
		}
		#endregion
	}
	#endregion
}